//
//  CCCycleScrollView.m
//  GGTV
//
//  Created by apple on 15/10/26.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "CCCycleScrollView.h"
@interface CCCycleScrollView()
@property (strong,nonatomic) NSMutableArray *imageViewArray;
@end

@implementation CCCycleScrollView


-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _ccImageArray = [NSMutableArray array];
        self.pagingEnabled = YES;
        [self addObserver:self forKeyPath:@"contentOffset" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld  context:nil];
    }
    return self;
}

-(void)dealloc
{
    [self removeObserver:self forKeyPath:@"contentOffset"];
}

-(void)layoutSubviews
{
  
    [self setImageViewArray:_ccImageArray];
    self.contentSize = CGSizeMake(self.frame.size.width * _imageViewArray.count, self.frame.size.height);
    for (UIImageView *temp in _imageViewArray) {
        [self addSubview:temp];
    }
}

-(void)setCcImageArray:(NSMutableArray *)ccImageArray
{
    _ccImageArray = ccImageArray;
}

-(NSMutableArray *)CCImageArray
{
    return _ccImageArray;
}

-(void)setImageViewArray:(NSMutableArray *)imageArray
{
    NSMutableArray *imageViewArray = [NSMutableArray array];
    if (imageArray.count == 1) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.frame];
        imageView.image = imageArray[0];
        [imageViewArray addObject:imageView];
    }else if (imageArray.count > 1){
        for (int i = 0; i < imageArray.count+2; i++) {
            CGRect frame = CGRectMake(self.frame.size.width * (i),
                                      0,
                                      self.frame.size.width,
                                      self.frame.size.height);
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:frame];
            if (i == 0) {
                imageView.image = [imageArray lastObject];
            }else if (i == imageArray.count + 1){
                imageView.image = [imageArray firstObject];
            }else{
                imageView.image = imageArray[i-1];
            }
            [imageViewArray addObject:imageView];
        }
    }
    _imageViewArray = imageViewArray;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGPoint point= [[change objectForKey:@"new"] CGPointValue];
        if (point.x == 0) {
            [self setContentOffset:CGPointMake(self.frame.size.width * (_imageViewArray.count-2), 0) animated:NO];
        }else if (point.x == self.frame.size.width * (_imageViewArray.count-1)){
            [self setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
        }
    }
}


@end
